package www.wen.com.common.lib.util

import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.media.MediaScannerConnection
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import www.wen.com.common.lib.app.BaseApplication
import www.wen.com.common.lib.util.FileUtils.copy
import java.io.*
import java.net.URLConnection

/**
 * @author WEN
 * @Description:
 * @date 2021/9/30 16:52
 */
object BitmapUtil {

    /**
     * 保存到相册
     * @param src  源图片
     * @param file 要保存到的文件
     */
    fun savePhotoAlbum(
        src: Bitmap,
        file: File,
        context: Context = BaseApplication.CONTEXT,
        onScanCompletedListener: MediaScannerConnection.OnScanCompletedListener,
    ) {
        if (isEmptyBitmap(src)) {
            return
        }
        //先保存到文件
        var outputStream: OutputStream
        try {
            outputStream = BufferedOutputStream(FileOutputStream(file))
            src.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
            if (!src.isRecycled) {
                src.recycle()
            }
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }
        //再更新图库
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val values = ContentValues()
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, file.name)
            values.put(MediaStore.MediaColumns.MIME_TYPE, getMimeType(file))
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM)
            val contentResolver = context.contentResolver
            val uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
                ?: throw Exception("图片保存失败")
            onScanCompletedListener.onScanCompleted(file.absolutePath,uri)
            try {
                outputStream = contentResolver.openOutputStream(uri)!!
                val fileInputStream = FileInputStream(file)
                copy(fileInputStream, outputStream)
                fileInputStream.close()
                outputStream.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        } else {
            MediaScannerConnection.scanFile(
                context,
                arrayOf(file.absolutePath),
                arrayOf("image/jpeg"),
                onScanCompletedListener
            )
        }
    }

    private fun getMimeType(file: File): String? {
        val fileNameMap = URLConnection.getFileNameMap()
        return fileNameMap.getContentTypeFor(file.name)
    }

    private fun isEmptyBitmap(src: Bitmap?): Boolean {
        return src == null
    }


    /**
     * 从View生成一张图片
     */
    fun generateBitmapFromView(
        view: View,
        config: Bitmap.Config = Bitmap.Config.ARGB_8888
    ): Bitmap {
        val bitmap: Bitmap = Bitmap.createBitmap(view.width, view.height, config)
        val canvas = Canvas(bitmap)
        view.draw(canvas)
        return bitmap
    }

}